package cc.loac.heba.tool;

import cc.loac.heba.pojo.CheckCode;
import cc.loac.heba.pojo.LoginToken;
import cc.loac.heba.service.CheckCodeService;
import cc.loac.heba.service.HeiService;
import cc.loac.heba.service.LoginTokenService;
import cc.loac.heba.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 定时任务类
 */
@Component
public class ScheduleTask {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    CheckCodeService checkCodeService;

    @Resource
    LoginTokenService loginTokenService;

    @Resource
    HeiService heiService;

    @Resource
    UserService userService;

    /**
     * 每 12 小时执行一次数据检查
     */
    @Scheduled(fixedRate = 43200000)
    public void removeExpiredCheckCode() {
        /*
          检查验证码和登录令牌垃圾数据
         */
        Date date = new Date();
        List<CheckCode> checkCodeList = checkCodeService.getAllCheckCode();
        List<Integer> expiredCodeIds = new ArrayList<>();

        List<LoginToken> loginTokenList = loginTokenService.getAllLoginToken();
        List<Integer> expiredTokenIds = new ArrayList<>();

        if (checkCodeList != null) {
            for (CheckCode checkCode: checkCodeList) {
                // 如果现在时间戳大于等于验证码到期的时间戳，就删除验证码
                if (checkCode.getExpirationTime().getTime() <= date.getTime()) {
                    expiredCodeIds.add(checkCode.getCodeId());
                }
            }
        }

        if (loginTokenList != null) {
            for (LoginToken loginToken: loginTokenList) {
                // 如果现在时间戳大于等于到期的时间戳，就删除 LoginToken
                if (loginToken.getExpirationTime().getTime() <= date.getTime()) {
                    expiredTokenIds.add(loginToken.getTokenId());
                }
            }
        }

        if (expiredCodeIds.size() > 0) {
            // 删除验证码
            int result = checkCodeService.removeCheckCodeByIds(expiredCodeIds);
            logger.info("Delete expired Code Count: " + result);
        }

        if (expiredTokenIds.size() > 0) {
            // 删除 LoginToken
            int result = loginTokenService.removeLoginTokenByIds(expiredTokenIds);
            logger.info("Delete expired LoginToken Count: " + result);
        }
    }
}
